<?php

namespace App;

use App\Models\AdminUser;
use App\Models\Department;
use Encore\Admin\Traits\DefaultDatetimeFormat;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Cache;

/**
 * @property  string name;
 * @property  string path;
 */
class Document extends BaseModel
{
    use DefaultDatetimeFormat;

    const CACHE_KEY = 'documents_cache_setting_all_collection_3344';

    protected $fillable = ['name', 'path', 'department_id', 'creator_id', 'role_type', 'type', 'slug', 'enabled'];

    public function creator()
    {
        return $this->belongsTo(AdminUser::class, 'creator_id');
    }

    public function department(): BelongsTo
    {
        return $this->belongsTo(Department::class);
    }

    public function fileUrl($action = 'download')
    {
        return file_preview_url($this->path, $this->name, $action);
    }

    public function download()
    {
        return sprintf('<a href="%s" download="%s" target="_blank" title="下载"><i class="fa fa-download"></i>%s</a>',
            $this->fileUrl(),
            $this->name,
            $this->name
        );
    }

    public static function slugOptions($type = 0): array
    {
        $data1 = [
            'patent_retrieval_template'   => '专利申请前查新检索报告模板',
            'patent_pf_template'          => '专利申请前评估评分指标',
            'transverse_promise_template' => '科研项目伦理与安全风险自查及防范承诺书',
            'book_filing_template'        => '计算机软件著作权登记备案表'
        ];
        $data2 = ['index_nav' => '首页导航图', 'login_bg' => '登录背景图'];

        if ($type == 1) {
            return $data1;
        } elseif ($type == 2) {
            return $data2;
        }
        return array_merge($data1, $data2);
    }

    public static function allSettingCollection(): Collection
    {
        return Cache::remember(self::CACHE_KEY, 3600, function () {
            return self::query()->where('type', '>', 0)->orderByDesc('id')->get();
        });
    }

    public static function forgetCache()
    {
        Cache::forget(self::CACHE_KEY);
    }
}
